package cool.taomu.toolkit.rpc.thrift.server.service

import java.net.InetSocketAddress
import org.apache.thrift.TProcessor
import org.apache.thrift.TProcessorFactory
import org.apache.thrift.protocol.TCompactProtocol
import org.apache.thrift.server.THsHaServer
import org.apache.thrift.transport.TNonblockingServerSocket
import org.apache.thrift.transport.layered.TFramedTransport
import org.slf4j.LoggerFactory

class ThriftServer {
	val static LOG = LoggerFactory.getLogger(ThriftServer);


	def static server(String host, int port, TProcessor processor) {
		val coreNumber = Runtime.getRuntime().availableProcessors;
		server(host, port, coreNumber, coreNumber * 2, processor);
	}

	def static server(String host, int port, int minWorkerThreads, int maxWorkerThreads, TProcessor processor) {
		LOG.info("启动服务 host:{},port:{}", host, port);
		LOG.info("minWorkerThreads:{},maxWorkerThreads:{}", minWorkerThreads, maxWorkerThreads);
		var socket = new TNonblockingServerSocket(new InetSocketAddress(host, port));
		var arg = new THsHaServer.Args(socket).minWorkerThreads(minWorkerThreads).maxWorkerThreads(maxWorkerThreads);
		arg.protocolFactory(new TCompactProtocol.Factory());
		arg.transportFactory(new TFramedTransport.Factory());
		arg.processorFactory(new TProcessorFactory(processor));
		var server = new THsHaServer(arg);
		server.serve();
	}

}
